package org.jspresso.framework.application.frontend.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jspresso.framework.util.accessor.IAccessor;
import org.jspresso.framework.util.accessor.IAccessorFactory;
import org.jspresso.framework.util.exception.NestedRuntimeException;

public class AddCollectionPropertyAsChildModuleFrontAction extends AddBeanAsSubModuleFrontAction {


  @Override
  protected List getComponentsToAdd(Map context) {
    List<?> componentsToAdd = getSelectedModels(context);
    if (getReferencePath() == null || componentsToAdd == null || componentsToAdd.isEmpty()) {
      return componentsToAdd;
    }

    try {
      IAccessorFactory accessorFactory = getBackendController(context).getAccessorFactory();
      List<Object> references = new ArrayList<>();
      for (Object component : componentsToAdd) {
        IAccessor accessor = accessorFactory.createPropertyAccessor(getReferencePath(), component.getClass());
        Object reference = accessor.getValue(component);
        references.add(reference);
      }
      return references;
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
      throw new NestedRuntimeException(e);
    }
  }
  
}
